package com.googlecode.garbagecan.springsecuritystudy.resmap;

import java.util.LinkedHashMap;
import java.util.Map;

import org.springframework.beans.factory.FactoryBean;
import org.springframework.security.ConfigAttributeDefinition;
import org.springframework.security.ConfigAttributeEditor;
import org.springframework.security.intercept.web.DefaultFilterInvocationDefinitionSource;
import org.springframework.security.intercept.web.FilterInvocationDefinitionSource;
import org.springframework.security.intercept.web.RequestKey;
import org.springframework.security.util.AntUrlPathMatcher;
import org.springframework.security.util.UrlMatcher;

public class MyHardcodeFilterInvocationDefinitionSourceFactoryBean implements FactoryBean {

	public boolean isSingleton() {
		return true;
	}

	public Class getObjectType() {
		return FilterInvocationDefinitionSource.class;
	}

	public Object getObject() {
		Object obj = new DefaultFilterInvocationDefinitionSource(this.getUrlMatcher(), this.buildRequestMap());
		System.out.println("obj: " + obj);
		return obj;
	}

	protected LinkedHashMap<RequestKey, ConfigAttributeDefinition> buildRequestMap() {
		LinkedHashMap<RequestKey, ConfigAttributeDefinition> requestMap = null;
		requestMap = new LinkedHashMap<RequestKey, ConfigAttributeDefinition>();

		ConfigAttributeEditor editor = new ConfigAttributeEditor();

		Map<String, String> resourceMap = new LinkedHashMap<String, String>();
		resourceMap.put("/", "ROLE_USER,ROLE_ADMIN");
		resourceMap.put("/admin*.jsp", "ROLE_ADMIN");
		resourceMap.put("/user*.jsp", "ROLE_USER,ROLE_ADMIN");
		resourceMap.put("/index.jsp", "ROLE_USER,ROLE_ADMIN");
		resourceMap.put("/tags.jsp", "ROLE_USER,ROLE_ADMIN");
		
		for (Map.Entry<String, String> entry : resourceMap.entrySet()) {
			RequestKey key = new RequestKey(entry.getKey(), null);
			editor.setAsText(entry.getValue());
			requestMap.put(key, (ConfigAttributeDefinition) editor.getValue());
		}
		System.out.println("requestMap: " + requestMap);
		return requestMap;
	}

	protected UrlMatcher getUrlMatcher() {
		return new AntUrlPathMatcher();
	}
}
